package com.export.netty.inithandler;//package rsj.netty.inithandler;
//
//import io.netty.bootstrap.ServerBootstrap;
//import io.netty.channel.ChannelFuture;
//import io.netty.channel.ChannelHandler;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.channel.SimpleChannelInboundHandler;
//import io.netty.channel.nio.NioEventLoopGroup;
//import io.netty.channel.socket.nio.NioServerSocketChannel;
//import io.netty.handler.codec.http.FullHttpRequest;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.context.event.ApplicationStartedEvent;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.ApplicationContextAware;
//import org.springframework.context.ApplicationListener;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.lang.NonNull;
//import org.springframework.stereotype.Component;
//
///**
// * @author       xuguoliang@rlyy.com
// * @date         2019/12/17 17:19
// * @description  主要用于事务的处理
// * @package      com.example.netty.inithandler
// */
//@ChannelHandler.Sharable
//@Component
//public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> implements ApplicationContextAware {
//
//
////    private static ConcurrentHashMap<String ,HashMap<String, String>> concurrentHashMap = new ConcurrentHashMap<String, HashMap<String, String>>();
//
//
//    @Override
//    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request)  {
//        System.out.println("HttpServerHandler channelRead0 开始执行····");
//
////        Box out = new Box();
////        HttpResponseStatus httpStatus = null;
////        try{
////
////            // 资源定位
////            // FullHttpRequest freq = request.copy();
////            String uri = request.uri();//uri 需要判断资源是否正确
////
////            //解析内容
////            String content = request.content().toString(CharsetUtil.UTF_8);
////            JSONObject jsonObject = JSONObject.parseObject(content);
////
////            //执行方法
////            String $api = jsonObject.getString("$api");// 获取执行api
////            if(concurrentHashMap.containsKey($api)) {
////                Box box = JsonHelper.json2Box(content);
////                HashMap<String, String> result = concurrentHashMap.get($api);
////                String methdoName = result.keySet().iterator().next();
////                String clazzName = result.get(methdoName);
////                Object entity = Class.forName(clazzName).newInstance();
////                Method method = Class.forName(clazzName).getDeclaredMethod(methdoName, Box.class);
////                out = (Box)method.invoke(entity, box);// 返回结果
////                httpStatus = HttpResponseStatus.OK;
////            } else {
////                httpStatus = HttpResponseStatus.UNAUTHORIZED;
////                throw new ThinkException(APICode_Enum.NOT_FIND.getKey(),"查不到API数据！");
////            }
////
////        } catch(ThinkException e){
////            out.setThinkException(e);
////        } catch (Exception e){
////
////            e.printStackTrace();
////        } finally {
////            //返回结果
////            // response(ctx, httpStatus ,out);
////            // ctx.writeAndFlush(out).addListener(ChannelFutureListener.CLOSE);
////            request.retain();
////            ctx.writeAndFlush(request).addListener(ChannelFutureListener.CLOSE);
////            //  ReferenceCountUtil.release(request);
////        }
//    }
//
//
//
//    @Override
//    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//
//        System.out.println("HttpServerHandler setApplicationContext 开始执行····");
//
////        Map<String, Object> handlers = applicationContext.getBeansWithAnnotation(NettyHandler.class);
////        for (Map.Entry<String, Object> entry : handlers.entrySet()) {
////            Object handler = entry.getValue();
////            for (Method method : handler.getClass().getMethods())
////            {
////                Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
////                for (Annotation ann:declaredAnnotations)
////                {
////                    if(ann.annotationType().getName().equals(NettyHandler.class.getName()))
////                    {
////                        String[] value = method.getAnnotation(NettyHandler.class).value();
////                        if(value != null)
////                        {
////                            for (String uri:value)
////                            {
////                                uri = uri.replace("/","");
////                                HashMap<String, String> submap = new HashMap<String, String>();
////                                submap.put(method.getName(),handler.getClass().getName());
////                                concurrentHashMap.put(uri, submap);
////                            }
////                        }
////                    }
////                }
////            }
////            System.err.println("请求api初始化：" + concurrentHashMap.toString());
////        }
//    }
//
//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        ctx.fireExceptionCaught(cause);
//    }
//
//
////    public static void response(ChannelHandlerContext ctx, HttpResponseStatus status, Box box) {
////        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status, Unpooled.copiedBuffer(box.toJson()+ "\r\n", CharsetUtil.UTF_8));
////        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
////        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
////    }
////
////
////    public static void main(String[] args) throws Exception{
////        Object obj = Class.forName("com.example.controller.DemoController").newInstance();
////        Method demo1Method = Class.forName("com.example.controller.DemoController").getDeclaredMethod("demo2Method", Box.class);
////        Box box = new Box();
////        box.putNode("testKey","testValue");
////        demo1Method.invoke(obj,box);
////    }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
////          executor.execute(() ->  handlerRequest(ctx, request));
////    private ExecutorService executor = Executors.newCachedThreadPool(runnable -> {
////        Thread thread = Executors.defaultThreadFactory().newThread(runnable);
////        thread.setName("HttpServerHandler-" + thread.getName());
////        return thread;
////    });
////    private void handlerRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
////        Box out = new Box();
////        HttpResponseStatus httpStatus = null;
////        try{
////
////            // 资源定位
////           // FullHttpRequest freq = request.copy();
////            String uri = request.uri();//uri 需要判断资源是否正确
////
////            //解析内容
////            String content = request.content().toString(CharsetUtil.UTF_8);
////            JSONObject jsonObject = JSONObject.parseObject(content);
////
////            //执行方法
////            String $api = jsonObject.getString("$api");// 获取执行api
////            if(concurrentHashMap.containsKey($api)) {
////                Box box = JsonHelper.json2Box(content);
////                HashMap<String, String> result = concurrentHashMap.get($api);
////                String methdoName = result.keySet().iterator().next();
////                String clazzName = result.get(methdoName);
////                Object entity = Class.forName(clazzName).newInstance();
////                Method method = Class.forName(clazzName).getDeclaredMethod(methdoName, Box.class);
////                out = (Box)method.invoke(entity, box);// 返回结果
////                httpStatus = HttpResponseStatus.OK;
////            } else {
////                httpStatus = HttpResponseStatus.UNAUTHORIZED;
////                throw new ThinkException(APICode_Enum.NOT_FIND.getKey(),"查不到API数据！");
////            }
////
////        } catch(ThinkException e){
////            out.setThinkException(e);
////        } catch (Exception e){
////
////            e.printStackTrace();
////        } finally {
////            //返回结果
////           // response(ctx, httpStatus ,out);
////           // ctx.writeAndFlush(out).addListener(ChannelFutureListener.CLOSE);
////            request.retain();
////            ctx.writeAndFlush(request).addListener(ChannelFutureListener.CLOSE);
////            ReferenceCountUtil.release(request);
////        }
////    }
//
//
//}
